package org.abratuhi.kvngroupware.pubsub;

import java.util.ArrayList;

public class HubSet {
	ArrayList<Hub> hubs = new ArrayList<Hub>();

	public HubSet(String[] attributes){
		// create hub structure
		for(int i=0; i<attributes.length; i++){
			hubs.add(new Hub(attributes[i]));
		}
	}
	
	public void addSubscription(Subscription sub){
		for(int i=0; i<hubs.size(); i++){
			hubs.get(i).addSubscription(sub);
		}
	}
	
	public void removeSubscription(Subscription sub){
		for(int i=0; i<hubs.size(); i++) hubs.get(i).removeSubscription(sub);
	}
	
	public void removeSubscriptions(String subscriberId){
		for(int i=0; i<hubs.size(); i++) hubs.get(i).removeSubscriptions(subscriberId);
	}
	
	public Subscription getSubscription(String subscriptionId){
		// TODO
		return null;
	}
	
	public ArrayList<Subscription> getSubscriptions(String subscriberId){
		ArrayList<Subscription> result = new ArrayList<Subscription>();
		if(hubs.size() > 0){
			result = hubs.get(0).getSubscriptions(subscriberId);
			if(hubs.size() > 1){
				for(int i=1; i<hubs.size(); i++){
					result = intersection(result, hubs.get(i).getSubscriptions(subscriberId));
				}
			}
		}
		return result;
	}
	
	public void updateSubscription(){
		// TODO
	}

	public ArrayList<Subscription> intersection(ArrayList<Subscription> l1, ArrayList<Subscription> l2){
		ArrayList<Subscription> result = new ArrayList<Subscription>();
		for(int i=0; i<l1.size(); i++){
			if(l2.contains(l1.get(i))){
				result.add(l1.get(i));
			}
		}
		return result;
	}

	public ArrayList<Subscription> match(Publication pub){
		ArrayList<Subscription> result = new ArrayList<Subscription>();
		if(hubs.size() > 0){
			result = hubs.get(0).match(pub);
			if(hubs.size() > 1){
				for(int i=1; i<hubs.size(); i++){
					result = intersection(result, hubs.get(i).match(pub));
				}
			}
		}
		return result;
	}
	
	public String toString(){
		String result = "hubset:\n";
		for(int i=0; i<hubs.size(); i++) result += hubs.get(i).toString();
		return result;
	}
}
